package top.lvkun.user.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.lvkun.basic.service.impl.BaseServiceImpl;
import top.lvkun.user.domain.Shopcart;
import top.lvkun.user.mapper.ShopcartMapper;
import top.lvkun.user.service.IShopcartService;

import java.math.BigDecimal;
import java.util.List;

@Service
public class ShopcartServiceImpl extends BaseServiceImpl<Shopcart> implements IShopcartService {

    @Autowired
    private ShopcartMapper shopcartMapper;

    /**
     * 商品详情页添加到购物车
     * @param shopcart
     */
    @Override
    @Transactional
    public void add(Shopcart shopcart) {
        //计算金额
        shopcart.setAmount(shopcart.getPrice().multiply(new BigDecimal(shopcart.getBuycount())));
        //通过user_id和product_id查询购物车数据
        Shopcart cart = shopcartMapper.findByUserIdAndProductId(shopcart.getUser_id(),shopcart.getProduct_id());
        if(shopcart.getId()==null){//添加购物车
            if(cart==null){
                shopcartMapper.save(shopcart);
            }else {
                //修改购买数量
                shopcart.setBuycount(cart.getBuycount()+shopcart.getBuycount());
                //修改小计金额
                shopcart.setAmount(cart.getAmount().add(shopcart.getAmount()));
                shopcartMapper.update(shopcart);
            }
        }else {//购物车页面修改数量，及金额
            shopcartMapper.update(shopcart);
        }


    }

    /**
     * 获取当前用户的购物车信息
     * @param userId
     */
    @Override
    public List<Shopcart> getShopcarts(Long userId) {
         return shopcartMapper.getShopcarts(userId);
        /*return AjaxResult.me().setSuccess(true).setData(shopcart);*/
    }
}
